package com.qingke.oms.command.shop;

import java.util.Set;

import com.qingke.oms.command.ShopCommand;
import com.qingke.oms.pojo.ItemQuantity;
import com.qingke.oms.pojo.Shop;
import com.qingke.oms.pojo.ShoppingCart;
import com.qingke.oms.pojo.ShoppingCartItem;
import com.qingke.oms.pojo.User;
import com.qingke.oms.util.OMSConsole;

public class DeleteFromShoppingCartCommand extends ShopCommand {

	public DeleteFromShoppingCartCommand(User user, Shop shop) {
		super(user, shop);
	}

	@Override
	public void execute() {
		if(!dao.isShoppingCartExistByCustomerAndShop(user, shop)){
			OMSConsole.println("The shopping cart is not existed.");
			OMSConsole.println("Please add goods to shopping cart first.");
			return ;
		}
		
		int goodsId=OMSConsole.getInt("goods id:");
		if(!dao.isGoodsExistById(goodsId)){
			OMSConsole.println("The id of the goods is not existed.");
			return ;
		}
		ShoppingCart shoppingCart=dao.selectShoppingCartByCustomerAndShop(user,shop);
		boolean isExist=false;
		ShoppingCartItem shoppingCartItem=null;
		Set<ShoppingCartItem> shoppingCartItems=shoppingCart.getShoppingCartItems();
		for(ShoppingCartItem item:shoppingCartItems){
			if(!item.isBeCleared()&&item.getGoods().getId()==goodsId){
				shoppingCartItem=item;
				isExist=true;
				break;
			}
		}
		if(!isExist){
			OMSConsole.println("There is no the id of the goods in your shopping cart.");
			return ;
		}
		
		int quantity=OMSConsole.getInt("quantity:");
		if(quantity==0){
			OMSConsole.println("cancel delete goods from shopping cart.");
			return ;
		}
		if(quantity>shoppingCartItem.getQuantity()){
			OMSConsole.println("The input is more than the quantity of the goods in the shopping cart.");
			OMSConsole.println("Default the input equal the quantity of the goods in the shopping cart.");
			OMSConsole.println("[new input]:"+shoppingCartItem.getQuantity());
			quantity=shoppingCartItem.getQuantity();
		}
		
		ItemQuantity itemQuantity=new ItemQuantity();
		itemQuantity.setQuantity(shoppingCartItem.getQuantity()-quantity);
		itemQuantity.setShoppingCartItem(shoppingCartItem);
		boolean isSuccess=dao.insertItemQuantity(itemQuantity);
		if(!isSuccess){
			OMSConsole.println("create item quantity failed.");
			return ;
		}
		shoppingCart=dao.selectShoppingCartByCustomerAndShop(user, shop);
		shoppingCart.calculateTotal();
		boolean isSuccessUpdate=dao.updateShoppingCart(shoppingCart);
		if(!isSuccessUpdate){
			OMSConsole.println("update shopping cart total failed.");
			OMSConsole.println("The total need be careful.");
			return ;
		}
		OMSConsole.println("Delete success.");
	}

}
